<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="场地名称" prop="name">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入场地名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="预约状态" prop="status" style="width: 300px">
        <el-select v-model="queryParams.status" placeholder="请选择预约状态" clearable >
          <el-option
              v-for="dict in field_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['field:field:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['field:field:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['field:field:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['field:field:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="fieldList" @selection-change="handleSelectionChange">
      <el-table-column v-if="userStore.roles[0]!=='student'" type="selection" width="55" align="center" />
<!--      <el-table-column label="${comment}" align="center" prop="id" />-->
      <el-table-column label="序号" align="center">
        <template #default="scope">
          {{ scope.$index + 1 +(queryParams.pageNum-1)*(queryParams.pageSize)}}
        </template>
      </el-table-column>
      <el-table-column label="场地名称" align="center" prop="name" />
      <el-table-column label="场地类型" align="center" prop="type.typeName" />
      <el-table-column label="场地图片" align="center" prop="images" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.images" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="预约状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="field_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="场地描述" align="center" prop="describe" />
      <el-table-column label="人数限制" align="center" prop="count" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['field:field:edit']">修改</el-button>
          <el-button link type="primary" icon="PieChart" @click="yySub(scope.row)" v-hasPermi="['yuyue:reservation:add']" v-if="userStore.roles[0]=='student'">预约</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['field:field:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
    <!-- 预约 -->
    <el-dialog title="预约" v-model="yyOpen" width="512px" append-to-body>
      <el-form :model="yyData" label-width="80px">
        <el-form-item label="预约时间">
        <div class="block">
          <el-date-picker
              v-model="time"
              type="datetimerange"
              range-separator="到"
              start-placeholder="起止时间"
              end-placeholder="结束时间"
          />
        </div>
        </el-form-item>
      <el-form-item label="预约说明">
        <el-input
            v-model="yyData.describe"
            :rows="3"
            type="textarea"
            placeholder="请输入预约说明"
            size="large"
        />
      </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="yyInfo" type="primary">预约</el-button>
          <el-button @click="yyCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加或修改场地对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="fieldRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="场地名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入场地名称" />
        </el-form-item>
        <el-form-item label="场地类型">
          <el-select v-model="form.type.typeName"  placeholder="请选择场地类型" @change="handleChange" clearable>
            <el-option
                v-for="dict in typeList"
                :key="dict.id"
                :label="dict.typeName"
                :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="场地图片" prop="images">
          <image-upload limit="1" v-model="form.images"/>
        </el-form-item>
<!--        <el-form-item label="预约状态" prop="status">-->
<!--          <el-radio-group v-model="form.status">-->
<!--            <el-radio-->
<!--                v-for="dict in field_status"-->
<!--                :key="dict.value"-->
<!--                :label="parseInt(dict.value)"-->
<!--            >{{dict.label}}</el-radio>-->
<!--          </el-radio-group>-->
<!--        </el-form-item>-->
        <el-form-item label="场地描述" prop="describe">
          <el-input v-model="form.describe" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="人数限制" prop="count">
          <el-input type="number" v-model="form.count" placeholder="请输入人数限制" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Field">
import { listField, getField, delField, addField, updateField } from "@/api/field/field";
import {listType} from "@/api/type/type.js";
const { proxy } = getCurrentInstance();
const { field_status } = proxy.useDict('field_status');
import useUserStore from '@/store/modules/user'
const userStore = useUserStore()
import {addReservation} from "@/api/yuyue/reservation.js";
const fieldList = ref([]);
const open = ref(false);
const yyOpen = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const time = ref('')
//预约数据
const yyData = reactive({
  userId:null,
  fieldId:null,
  useTime:null,
  endTime:null,
  describe:null
})

function yyCancel(){
  yyReset()
  yyOpen.value = false;
}

function yyReset(){
  yyData.userId = null
  yyData.fieldId = null
  yyData.useTime = null
  yyData.endTime = null
  yyData.describe = null
  time.value = '';
}

function yyInfo(){
  if (time.value.length<2){
    alert('请输入预约时间')
    return
  }
  yyData.useTime = time.value[0]
  yyData.endTime = time.value[1]
  console.log(yyData)
  addReservation(yyData).then(response => {
    proxy.$modal.msgSuccess("预约成功");
    yyOpen.value = false;
  });
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    status: null,
  },
  rules: {
    name:[{ required: true, message: '请输入场地名称', trigger: 'blur' }],
    count:[{ required: true, message: '请输入场地限制的人数', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

function handleChange(value){
  form.value.typeId = value
}

/** 查询场地列表 */
function getList() {
  loading.value = true;
  listField(queryParams.value).then(response => {
    fieldList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    typeId: null,
    images: null,
    type:{id:null,typeName:''},
    status: 0,
    describe: null,
    count: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  proxy.resetForm("fieldRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  getTypeList();
  reset();
  open.value = true;
  title.value = "添加场地";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getField(_id).then(response => {
    getTypeList();
    form.value = response.data;
    open.value = true;
    title.value = "修改场地";
  });
}

function yySub(row){
  yyOpen.value =true
  yyData.userId = userStore.id
  yyData.fieldId = row.id
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["fieldRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        const backEndData ={
          id: form.value.id,
          name: form.value.name,
          type: {id:form.value.typeId},
          images: form.value.images,
          status: form.value.status,
          describe: form.value.describe,
          count: form.value.count,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          remark: null
        }
        updateField(backEndData).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        const backEndData ={
          name: form.value.name,
          type: {id:form.value.typeId},
          images: form.value.images,
          status: form.value.status,
          describe: form.value.describe,
          count: form.value.count,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          remark: null
        }
        addField(backEndData).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除场地编号为"' + _ids + '"的数据项？').then(function() {
    return delField(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('field/field/export', {
    ...queryParams.value
  }, `field_${new Date().getTime()}.xlsx`)
}

const typeList = ref([]);
function getTypeList(){
  listType().then(response => {
    typeList.value = response.rows;
  });
}
getList();
</script>
